package com.admin.socketmultiplayer

import android.os.Handler
import android.os.Handler.Callback
import com.admin.socketmultiplayer.activity.MyApplication
import com.admin.socketmultiplayer.config.FixedValue
import com.socks.library.KLog
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.net.Socket
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import android.R.attr.port
import android.system.Os.socket
import java.net.InetSocketAddress


/**
 * Created by 吴昶 on 2018/4/25.
 */
class TestSocketConnection(var handler:Handler,var roomId:String):Runnable{

    var serverIp=MyApplication.getSharedPreferencesString(FixedValue.SERVER_IP, FixedValue.CONNECTION_IP)
    private var msgFormat="utf-8"
    var socket:Socket?=null
    private var reader:BufferedReader?=null
    private var writer:PrintWriter?=null
    var exector:ExecutorService?=null
    var userList=ArrayList<String>()
    var keepConnection=true
    var msg=""
    var timer:Timer?=null
    var waitTime=0

    fun connection(){

            Thread{
                try {
//                    socket = Socket(serverIp, 8999)
                    socket = Socket()
                    socket!!.connect(InetSocketAddress(serverIp, 8999), 4000)
                    reader = BufferedReader(InputStreamReader(socket!!.getInputStream(),msgFormat))
                    writer = PrintWriter(OutputStreamWriter(socket!!.getOutputStream(),msgFormat))
                    exector=Executors.newCachedThreadPool()
                    exector!!.execute(this)
                    handler.sendEmptyMessage(-1)
//                    timer= Timer()
//                    timer!!.schedule(timerTask,1000,1000)
                }catch (e:Exception){
                    KLog.d("9999999999999")
                    KLog.e(e.toString())
                    handler.sendEmptyMessage(111)
                }
            }.start()

    }


    override fun run() {
        while (keepConnection){
            socket?.let {
                if(!socket!!.isClosed){
                    if(socket!!.isConnected){
                        if(!socket!!.isOutputShutdown){
                            try {
                                var msg=reader!!.readLine()
                                if(msg==null) msg=""
                                var message=handler.obtainMessage()
                                message.what=0
                                message.obj=msg
                                handler.sendMessage(message)
                            }catch (e:Exception){
                                KLog.e(e.message.toString())
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 关闭连接
     */
    fun close(){
        msg="close"
        exector!!.execute(closeRunnable)
    }

    var closeRunnable= Runnable {
        run{
            try {
                writer!!.println(msg)
                writer!!.flush()
                socket!!.close()
                keepConnection = false
                stopTimer()
            }catch (e:Exception){
                KLog.e(e.message)
            }
        }
    }

    /**
     * 停止计时
     */
    fun stopTimer(){
        timer?.let {
            timer!!.cancel()
            timer=null
        }
    }

    /**
     * 发送消息
     */
    fun sendMsg(str:String){
        msg=str
        exector?.let {
            exector!!.execute(sendRunnable)
        }
    }

    var sendRunnable= Runnable {
        run{
            try {
                writer!!.println(msg)
                writer!!.flush()
            }catch (e:Exception){
                KLog.e(e.message)
            }
        }
    }

    var timerHandler=Handler(Callback {
        when(it.what){
            1001->{
                waitTime++
                if(waitTime==10){
                    sendMsg("checkConnection,$roomId")
                    waitTime=0
                }
            }
        }
        false
    })

    var timerTask=object :TimerTask(){
        override fun run() {
            KLog.d("======")
            timerHandler.sendEmptyMessageDelayed(1001,1000)
        }
    }

    fun addRoom(msg:String){
        sendMsg(msg)
    }

    /**
     * 终止答题
     */
    fun cutOut(roomId: String,userId:String){
        socket?.let { socket!!.close() }
        keepConnection=false
        sendMsg("outRoom,$roomId,$userId")
        stopTimer()
    }


}